package sg.edu.nus.iss.billing.controller;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import sg.edu.nus.iss.billing.exceptions.ControllerException;
import sg.edu.nus.iss.billing.model.bill.BillingPeriod;
import sg.edu.nus.iss.billing.utils.DateHelper;

/**
 * @author ZiFeng, Thurien, YinNi
 *
 */
public class GSTRateContrller {

	private static String dataLocation = "data/inbound/Charges/GSTRate.txt";

	public static Date getCurrentEffectiveDate(BillingPeriod billPeriod, Set<Date> effectiveDates)  {

		Date tempEffectiveDate = null;
		for (Date date : effectiveDates)
			// get the closet effective date
			//if (tempEffectiveDate == null)

				if (date.before(billPeriod.getStartDate())
						&& (tempEffectiveDate == null || date.after(tempEffectiveDate)))
					tempEffectiveDate = date;
		return tempEffectiveDate;
	}

	public static double getCurrentRate(BillingPeriod period) throws ControllerException {
		try {
			Map<Date, Double> rates = readAllRates();
			Set<Date> effectiveDates = rates.keySet();
			Date currentEffectiveDate = getCurrentEffectiveDate(period, effectiveDates);
			return rates.get(currentEffectiveDate);
		} catch (Exception e) {
			e.printStackTrace();
			throw new ControllerException("Exception while fetching the charges for the service ");
		}

	}

	public static Map<Date, Double> readAllRates() throws IOException {
		Map<Date, Double> allRates = new HashMap<Date, Double>();
		try {
			BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(dataLocation)));
			double rate = 0.0;
			String line = null;
			while ((line = bufferedReader.readLine()) != null) {
				String[] strs = line.split(",");
				if (strs != null && strs.length == 2) {
					Date effectiveDate = DateHelper.getDate(strs[0]);

					rate = Double.parseDouble(strs[1]);
					allRates.put(effectiveDate, rate);
				}
			}
			bufferedReader.close();
			return allRates;

		} catch (Exception e) {
			e.printStackTrace();
			throw new IOException("Exception while fetching the charges for the service ");
		}
	}
}
